mui.init();
//获取本地信息
var my_phone = localStorage.getItem("my_phone");
var user_id = localStorage.getItem("user_id");
//公共变量
var leaberid; //加入购物车或立即购买变量
//获得slider插件对象
var gallery = mui('.mui-slider');
gallery.slider({
	interval: 2000 //自动轮播周期，若为0则不自动播放，默认为0；
});

//店铺
$(document).on('tap', ".index", function() {
	var merchant_id = $(this).attr('merchant_id'); //商家id
	mui.openWindow({
		url: "shop_details.html",
		extras: {
			merchant_id: merchant_id
		},

	})
});

//客服
document.getElementById('service').addEventListener('tap', function() {
	mui.openWindow({
		url: "../my/my_online_service.html",
		id: "my_online_service",
	})
});

//购物车
document.getElementById('shopping').addEventListener('tap', function() {
	window.top.location.href = '../Shopping_Cart/Shopping_Cart.html';
});

//打开选择分类页面
document.getElementById('join_cart_btn').addEventListener('tap', function() {
	leaberid = $(this).attr('leaberid'); //购物车
	$(".mui-backdrop").css("display", "block");
	$('.mui-content').css('overflow', 'hidden');
	//console.log('加入购物车，选择规格层');
	
	//加入购物车，选择规格层
	$("#item_number").val('1')
	var htmlSpec = "";
	var specData = detailInfo.goods_info.goods_sku;
	for(var i = 0; i < specData.length; i++) {
		htmlSpec += '<p onclick="specSelect('+specData[i].sku_id+','+specData[i].price+','+i+')">'+specData[i].sku_name+'</p>'
	}	
	$('.spec-box').html(htmlSpec);
	specSelect(specData[specData.length -1].sku_id,specData[specData.length -1].price);
	$('.spec-box p').eq(specData.length -1).addClass('active')
	setTimeout(function(){	
	},500);
});
function specSelect(id,priceVal,index){	
	$('.spec-box p').removeClass('active')
	$('.spec-box p').eq(index).addClass('active')
	var specData = detailInfo.goods_info.goods_sku;
	for(var i = 0; i < specData.length; i++) {
		if(specData[i].sku_id==id){
			nameCartAdd = specData[i].sku_name;
		}
	}
//	console.log(id+' '+nameCartAdd+' '+priceVal);
	idCartAdd = id;
	priceCartAdd = priceVal;
	$('#shopping_price').text(priceCartAdd);
}
document.getElementById('buy_cart_btn').addEventListener('tap', function() {
//	console.log('立即购买');
	leaberid = $(this).attr('leaberid'); //立即购买
	$(".mui-backdrop").css("display", "block");
	$(".mui-content").css('overflow', 'hidden');
	$("#item_number").val('1')
	var htmlSpec = "";
	var specData = detailInfo.goods_info.goods_sku;
	for(var i = 0; i < specData.length; i++) {
		htmlSpec += '<p onclick="specSelect('+specData[i].sku_id+','+specData[i].price+','+i+')">'+specData[i].sku_name+'</p>'
	}	
	$('.spec-box').html(htmlSpec);
	specSelect(specData[specData.length -1].sku_id,specData[specData.length -1].price);
	$('.spec-box p').eq(specData.length -1).addClass('active')
	setTimeout(function(){	
	},500);
});
//打开选择分类页面
document.getElementById('close_icon').addEventListener('tap', function() {
	$(".mui-backdrop").css("display", "none")
	$(".mui-content").css('overflow', 'visible');
});

//点击li时变颜色
mui(".changecolor").on('touchstart', 'span', function() {
	this.style.color = '#e93b3d'
});
mui(".changecolor").on('touchend', 'span', function() {
	this.style.color = '#a6a6a6'
});

//关闭当前页面，返回上一个页面
mui('body').on('tap', '.return_back', function() {
	mui.back();
});

var id; //商品id
var detailInfo = '';
//查询商品详情
function itemDetails() {
	console.log('商品ID');
	console.log(id);
	plus.nativeUI.showWaiting("加载中...");
	mask.show(); //显示遮罩层
	var sellPhone;
	
	//商品详情
	mui.ajax(goods_url + '/api/goods/goodsInfo', {
		data: {
			"goods_id": id,
		},
		dataType: 'json', //服务器返回json格式数据
		type: 'post', //HTTP请求类型
		timeout: 10000, //超时时间设置为10秒；
		success: function(data) {
			console.log('商品详情接口')
			console.log(JSON.stringify(data));
			plus.nativeUI.closeWaiting(); //关闭等待
			mask.close(); //关闭遮罩层
			if(data.code == 1000) {
				detailInfo = data.resp;
				var merchant_id = data.resp.shop_info.shop_id; //商家ID
				$(".index").attr('merchant_id', merchant_id); //给商家id赋值
				$("#img").val(data.resp.image); //商品图片
				$("#commercial").val(data.resp.business_name); //商家
				$("#url").val(data.resp.url); //图片地址
				//点击购物车绑定数据
				$("#shopping_title").text(data.resp.goods_info.goods_name); //商品名称
				$("#shopping_price").text(data.resp.goods_info.price); //商品价格
				var detailPicture = data.resp.goods_info.img_list;
				var detail_diagram = data.resp.goods_info.album_picture.pic_cover; //商品详情图
				var image_url = data.resp.url; //图片地址
				var detail_img = detail_diagram; //商品详情图
//				console.log(urlPic+detail_img);
				// $("#details_img").html(urlPic+detail_img);
				//商品详情
				$("#details_img").html(data.resp.goods_info.description);
				
				var abbreviation_diagram = data.resp.image; //缩约图
				var abbreviation_diagram2 = urlPic + detailPicture[0].pic_cover_mid; //缩约图
				$("#abbreviation_diagram").attr('src', abbreviation_diagram2);
//				var Sowing_map = data.resp.item_desc; //轮播图
//				if(Sowing_map != null) {
//					var sowing_map = Sowing_map.split(","); //截取字符串变成数组
//				}
				var imgss = '../../images/detais_img.png';			
//				console.log('2232323');
//				console.log(detailPicture.length);
				
				//轮播图绑定
				var img_html = '';
				var img_html2 = '<div class="mui-indicator mui-active" style="width:15px;height:4px;"></div>';
				if(detailPicture == null) {
					$("#last_img").attr('src', imgss);
					$("#frist_img").attr('src', imgss);
					img_html += '<div class="mui-slider-item">';
					img_html += '<a href="#"><img src="../../images/detais_img.png"/></a>';
					img_html += '</div>';
					img_html2 += '<div class="mui-indicator" style="width:15px;height:4px;"></div>';
				}
				else {
					for(var i = 0; i < detailPicture.length; i++) {
						$("#last_img").attr('src', urlPic + detailPicture[i].pic_cover_mid);
						$("#frist_img").attr('src', urlPic + detailPicture[0].pic_cover_mid);
						img_html += '<div class="mui-slider-item">';
						img_html += '<a href="#"><img src=' + urlPic + detailPicture[i].pic_cover_mid + '></a>';
						img_html += '</div>';
					}
					for(var i = 1; i < detailPicture.length; i++) {
						img_html2 += '<div class="mui-indicator" style="width:15px;height:4px;"></div>';
					}
				}
				$("#frist_img_box").before(img_html);
				$("#index_dian").html(img_html2);
				var gallery = mui('.mui-slider');
				gallery.slider({
					interval: 2000 //自动轮播周期，若为0则不自动播放，默认为0；
				});
				var html = "";
				var goodsSkuLen = data.resp.goods_info.goods_sku.length;
//				$("#shopping_price").text(data.resp.goods_info.goods_sku[goodsSkuLen -1].price); //商品价格
				html += '<p class="antistop_text">' + data.resp.goods_info.goods_name + '</p>';
				html += '<p class="discount_price">￥<span>' + data.resp.goods_info.goods_sku[goodsSkuLen -1].price + '</span><span class="discount_price_span">价格<i>￥' + data.resp.goods_info.goods_sku[goodsSkuLen -1].promote_price + '</i></span></p>';
				html += '<div class="price_delet_box mui-clearfix">';
//				html += '<p class="price_delet mui-pull-left">返权益积分（商品价*20%）：<span>' + (data.resp.price * 0.2).toFixed(2) + '</span></p>';
				
				
				
				
				
				
				html += '</div>';
//				html += '<div class="oneself">';
//				if(data.resp.business_name == null) {
////					html += '<p class="mui-pull-left"><span>权益积分只能在特惠专区里消费</span></p>';
//					html += '<p class="oneself_icon mui-pull-right">平台自营</p>';
//				}
//				else {
////					html += '<p class="mui-pull-left"><span>权益积分只能在特惠专区里消费</span></p>';
//					html += '<p class="oneself_icon mui-pull-right">' + data.resp.goods_info.goods_name + '</p>';
//				}
//				html += '</div>';
				$('#slideshow_list').append(html);
				
				//销量 平台自营条
				if(data.resp.sales_volume == null) {
					$('.sell_barsg_1').html('销量&nbsp;0');
				}
				else {
					$('.sell_barsg_1').html('销量&nbsp;' + data.resp.sales_volume + '');
				}			
				var shopNameLnln = data.resp.goods_info.goods_name;
				//代售id找用户电话号码信息
				if(sell_id!=undefined){
					console.log(sell_id);
					mui.ajax(goods_url + '/api/user/getOneTel', {
						data:{
							id:sell_id
						},
						dataType: 'json', //服务器返回json格式数据
						type: 'post', //HTTP请求类型
						timeout: 10000, //超时时间设置为10秒；
						success: function(data) {
							console.log(JSON.stringify(data));
							sellPhone = data.resp;
							sellPhone  = data.resp.substr(0, 3) + '****' + data.resp.substring(7, 11)
							$('.sell_barsg_2').html(sellPhone);							
						},
						error: function(xhr, type, errorThrown) { //异常处理；
							console.log('商品详情接口失败');
						}
					});
				}
				else{
					if(data.resp.business_name == null) {
						$('.sell_barsg_2').html('银遇自营');				
					}
					else {
						$('.sell_barsg_2').html(shopNameLnln);
					}
				}
								
				//店铺信息				
				var htmlShop = "";
				htmlShop += '<a href="javascript:;" class="mui-navigate-right">'
				htmlShop += '<img class="mui-media-object mui-pull-left" src="../../images/store_z.png">'
				htmlShop += '<div class="mui-media-body" style="line-height: 40px;">' + data.resp.shop_info.shop_name + '</div>'
				htmlShop += '</a>';
				$('.shop-info-bar').html(htmlShop);

				/*规格*/
				//console.log(JSON.stringify(data.resp.ext2));
				var ext2 = data.resp.ext2;
				var json = JSON.parse(ext2);
				if(json.size != "") {
					var size = json.size.split(",");
					console.log(size.length);
					var size_html = "<p>尺码</p><span class='choose_color'>" + size[0] + "</span>&nbsp;"; //颜色
					for(var i = 1; i < size.length; i++) {
						//如果有空的不做显示
						size_html += "<span>" + size[i] + "</span>&nbsp;";
					}
					$(".size").html(size_html);
				}

				if(json.spec.bool == "success") { //11/21
					if(json.spec.resp != "") {
						var spec = json.spec.resp;
						//console.log(JSON.stringify(spec));
						var spec_html = "<p>规格</p>" +
							"<p><span sta=" + spec[0].price + " class='choose_color'>" + spec[0].spec + "</span></p>"; //尺寸
						for(var i = 1; i < spec.length; i++) {
							spec_html += "<p><span sta=" + spec[i].price + ">" + spec[i].spec + "</span></p>";
						}
						$(".spec").html(spec_html);
						var sta = $(".spec .choose_color").attr("sta"); //
						$("#shopping_price").text(sta); //商品价格 
					}
				}								
			}
			
			
			
		},
		error: function(xhr, type, errorThrown) { //异常处理；
			console.log('商品详情接口失败');
		}
	});
	
	
	
}

//选择颜色
$(document).on('tap', ".spec span", function() {
	$(this).addClass("choose_color").parent().siblings().children().removeClass("choose_color");
	var sta = $(this).attr("sta");
	$("#shopping_price").text(sta); //商品价格 
});

//选择尺寸
$(document).on('tap', ".size span", function() {
	$(this).addClass("choose_color").siblings().removeClass("choose_color");
});
var idCartAdd;
var nameCartAdd;
var priceCartAdd;
//加入购物车及立马购买
$(document).on('tap', '#join_cart_surebtn', function() {
	var spec = $(".spec .choose_color").text(); //尺寸
	var size = $(".size .choose_color").text(); //颜色 
	priceCartAdd = $("#shopping_price").text(); //单价价格  
	if(user_id == null) {
		mui.openWindow({
			url: '../user/login.html',
			createNew: true
		})
		return false;
	}
	if(leaberid == 1) { //添加到购物车
		console.log('leaberid=1');
		plus.nativeUI.showWaiting("加载中...");
		mask.show(); //显示遮罩层
		
		var item_number = $("#item_number").val(); //获取购买
		var specData = detailInfo.goods_info.goods_sku;
		if(idCartAdd==undefined){
			idCartAdd = detailInfo.goods_info.goods_sku[specData.length-1].sku_id;
			nameCartAdd = detailInfo.goods_info.goods_sku[specData.length-1].sku_name;
		}
		
		var dataAddCar = {
				"goods_id": id,
				"goods_name":detailInfo.goods_info.goods_name,
				"shop_id":detailInfo.shop_info.shop_id,
				"shop_name":detailInfo.shop_info.shop_name,
				"num": item_number,
				"sku_id": idCartAdd,
				"sku_name": nameCartAdd,
				"price": priceCartAdd,
				"picture_id": 1
		}		
		console.log(JSON.stringify(dataAddCar));
		
		mui.ajax(goods_url + '/api/cart/addCart', {
			data: {
					"goods_id": id,
					"goods_name":detailInfo.goods_info.goods_name,
					"shop_id":detailInfo.shop_info.shop_id,
					"shop_name":detailInfo.shop_info.shop_name,
					"num": item_number,
					"sku_id": idCartAdd,
					"sku_name": nameCartAdd,
					"price": priceCartAdd,
					"picture_id": 1
			},
			dataType: 'json', //服务器返回json格式数据
			type: 'post', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			success: function(data) {
				console.log('添加购物车接口成功！');
				console.log(JSON.stringify(data));
				plus.nativeUI.closeWaiting(); //关闭等待
				mask.close(); //关闭遮罩层
				if(data.code == -9){
					mui.alert(data.msg)
					return false
				}
				if(data.code == 1000) {
					mui.toast("添加成功", {
						duration: 'short',
						type: 'div' /* 是否使用h5绘制的对话框 */
					})
					$(".mui-backdrop").css("display", "none")
					$(".mui-content").css('overflow', 'visible');
				}
			},
			error: function(xhr, type, errorThrown) { //异常处理；
				console.log('详情接口失败');
				plus.nativeUI.closeWaiting(); //关闭等待
				mask.close(); //关闭遮罩层
//				var error_msg = JSON.parse(xhr.responseText)
//				mui.alert(error_msg.msg)
			}
		});
	}
	if(leaberid == 2) {
		console.log('leaberid=2');
		var item_pricing = $("#shopping_price").text(); //商品单价
		var single_number = $("#item_number").val(); //下单数量
		var total_commodity_price = Number(item_pricing) * Number(single_number); //商品总价
		var image = $("#img").val(); //商品图片
		var title = $(".antistop_text").text(); //商品名称 
		var commercial = $("#commercial").val(); //商家
		var url = $("#url").val(); //图片地址
		
		
		plus.nativeUI.showWaiting("加载中...");
		mask.show(); //显示遮罩层
		var item_number = $("#item_number").val(); //获取购买
		var specData = detailInfo.goods_info.goods_sku;
		if(idCartAdd==undefined){
			idCartAdd = detailInfo.goods_info.goods_sku[specData.length-1].sku_id;
			nameCartAdd = detailInfo.goods_info.goods_sku[specData.length-1].sku_name;
		}
		
		var dataBuyNow = {
				"tag": 'buy_now',
				"sku_id":idCartAdd,
				"num": item_number,
		}		
		console.log(JSON.stringify(dataBuyNow));
		
		mui.ajax(goods_url + '/api/Member/ordercreatesession', {
			data: {
					"tag": 'buy_now',
					"sku_id":idCartAdd,
					"num": item_number,
			},
			dataType: 'json', //服务器返回json格式数据
			type: 'post', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			success: function(data) {
				console.log('立即购买接口成功！');
				console.log(JSON.stringify(data));
				plus.nativeUI.closeWaiting(); //关闭等待
				mask.close(); //关闭遮罩层
				if(data.code == -9){
					mui.alert(data.msg)
					return false
				}
				if(data.code == 1000) {
					mui.toast("添加成功", {
						duration: 'short',
						type: 'div' /* 是否使用h5绘制的对话框 */
					})
					mui.openWindow({
						url: '../Shopping_Cart/Order_information.html',
						createNew: true
					})
					$(".mui-backdrop").css("display", "none")
					$(".mui-content").css('overflow', 'visible');
				}
			},
			error: function(xhr, type, errorThrown) { //异常处理；
				console.log('详情接口失败');
				plus.nativeUI.closeWaiting(); //关闭等待
				mask.close(); //关闭遮罩层
			}
		});
		
//		mui.openWindow({
//			url: '../Shopping_Cart/Order_information.html',
//			id: 'Order_information',
//			extras: {
//				leaberid: 2,
//				price: item_pricing,
//				item_number: single_number,
//				goodsid: id,
//				Total_price: total_commodity_price,
//				img: image,
//				name: title,
//				business: commercial,
//				imgurl: url,
//				specs: spec,
//				sizes: size
//			},
//			createNew: true
//		})
		
	}
})
var mask = mui.createMask(); //遮罩层
//页面进入执行方法
window.onload = function() {
	mui.plusReady(function() {
		var self = plus.webview.currentWebview();
		id = self.commodity_id;
		sell_id = self.sell_id;
		itemDetails();
		plus.nativeUI.closeWaiting(); //关闭等待
	})
}